//
//  XcodeCleanHomeVC.swift
//  ZJTools
//
//  Created by 万孟超 on 2023/11/17.
//

import Cocoa
import SnapKit

class XcodeCleanHomeVC: BaseVC {
    lazy var viewModel = XcodeCleanHomeVM()
    lazy var analyseButton: NSButton = {
        let button = NSButton()
        button.bezelStyle = .inline
        button.wantsLayer = true
        button.target = self
        button.action = #selector(startAnalyse)
        button.attributedTitle = NSAttributedString(string: "开始分析", attributes: [.font: NSFont.systemFont(ofSize: 14), .foregroundColor: NSColor.white])
        button.layer?.cornerRadius = 20
        button.layer?.backgroundColor = NSColor.randomColor(alpha: 0.4).cgColor
        return button
    }()
    
    lazy var cleanButton: NSButton = {
        let button = NSButton()
        button.bezelStyle = .inline
        button.wantsLayer = true
        button.target = self
        button.action = #selector(cleanXcode)
        button.attributedTitle = NSAttributedString(string: "一键清理", attributes: [.font: NSFont.systemFont(ofSize: 14), .foregroundColor: NSColor.white])
        button.layer?.cornerRadius = 20
        button.layer?.backgroundColor = NSColor.randomColor(alpha: 0.4).cgColor
        button.alphaValue = 0
        return button
    }()
    
    lazy var contentLabel: NSTextField = {
        let titleLabel = NSTextField()
        titleLabel.isVerticalCenter = true
        titleLabel.font = .systemFont(ofSize: 14)
        titleLabel.isBordered = false
        titleLabel.isEditable = false
        titleLabel.isSelectable = false
        titleLabel.textColor = .randomColor()
        titleLabel.bezelStyle = .roundedBezel
        titleLabel.backgroundColor = .clear
        titleLabel.lineBreakMode = .byTruncatingTail
        titleLabel.stringValue = "需要对\"~/Library/Developer\"文件夹授权才能进行分析"
        return titleLabel
    }()
    
    lazy var tableView: NSTableView = {
        let table = NSTableView()
        table.headerView = nil
        table.rowHeight = 52
        table.delegate = self
        table.dataSource = self
        table.style = .automatic
        table.rowSizeStyle = .custom
        table.focusRingType = .none
        table.backgroundColor = .clear
        let tableColumn = NSTableColumn(identifier: .init("tableColumn"))
        tableColumn.width = 368
        table.addTableColumn(tableColumn)
        table.alphaValue = 0
        table.selectionHighlightStyle = .none
        table.register(nil, forIdentifier: .init("XcodeCleanHomeCell"))
        return table
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func installSubViews() {
        view.addSubview(analyseButton)
        analyseButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 100, height: 40))
        }
        
        view.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(analyseButton.snp.bottom).offset(12)
        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(contentLabel.snp.bottom).offset(12)
            make.width.equalTo(400)
            make.height.equalTo(280)
        }
        
        view.addSubview(cleanButton)
        cleanButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(tableView.snp.bottom).offset(12)
            make.width.equalTo(100)
            make.height.equalTo(40)
        }
    }
    
    override func loadView() {
        let visualEffectView = NSView()
        visualEffectView.wantsLayer = true
        visualEffectView.layer?.backgroundColor = NSColor.clear.cgColor
        visualEffectView.frame = NSRect(origin: .zero, size: CGSize(width: 640, height: 650))
        view = visualEffectView
    }
    
    @objc func startAnalyse() {
        XcodeCleanManager.shared.analyse {
            NotiManager.remove(self)
            self.analyseButton.stopAnimation()
        }
        analyseButton.addAnimatedGradientBorder()
        NotiManager.add(self, name: .XcodeCleanHomeStatistics) { _, userInfo in
            if let index = userInfo?["index"] as? Int {
                Async(.main) { [self] in
                    tableView.reloadData(forRowIndexes: IndexSet(integer: index - 1), columnIndexes: IndexSet(integer: 0))
                }
            }
        }
        freshSubviews()
    }
    
    @objc func cleanXcode() {
        cleanButton.addAnimatedGradientBorder()
        viewModel.cleanData {[weak self] index in
            Async(.main) {
                self?.tableView.reloadData(forRowIndexes: IndexSet(integer: index - 1), columnIndexes: IndexSet(integer: 0))
            }
        }
        cleanButton.stopAnimation()
    }
    
    func freshSubviews() {
        NSAnimationContext.runAnimationGroup { context in
            context.duration = 1
            context.allowsImplicitAnimation = true
            context.timingFunction = .init(name: .easeOut)
            analyseButton.snp.updateConstraints { make in
                make.centerY.equalTo(-180)
            }
            tableView.alphaValue = 1
            cleanButton.alphaValue = 1
            view.layoutSubtreeIfNeeded()
        }
    }
}

extension XcodeCleanHomeVC: NSTableViewDelegate, NSTableViewDataSource {
    func numberOfRows(in tableView: NSTableView) -> Int {
        XcodeCleanManager.CleanModelType.count
    }
    
    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        var cellView = tableView.makeView(withIdentifier: .init("XcodeCleanHomeCell\(row)"), owner: self) as? XcodeCleanHomeCell
        if cellView == nil {
            cellView = XcodeCleanHomeCell()
            cellView?.identifier = .init("XcodeCleanHomeCell\(row)")
            cellView?.title = XcodeCleanManager.CleanModelType.currentTitle(row)
        }
        cellView?.size = XcodeCleanManager.CleanModelType.indexModel(row).size
        cellView?.isOn = viewModel.isContains(row)
        cellView?.cleanBlock = {[weak self] isOn in
            guard let self = self else { return }
            self.viewModel.freshListType(row, isAdd: isOn)
        }
        return cellView
    }
    
}
